package cn.com.xyc.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class ALiYunTool {
	public static String uploadGroupIcon(File file, String bucketName,
			String uploadPath) throws FileNotFoundException {
		OSSClient client = new OSSClient(ApplicationConstants.endpoint,
				ApplicationConstants.accessKeyId,
				ApplicationConstants.accessKeySecret);

		List<Bucket> buckets = client.listBuckets();

		// 检查Bucket是否存在
		boolean checkBuckets = false;
		for (Bucket bucket : buckets) {
			if (bucket.getName().equals(bucketName))
				checkBuckets = true;
		}
		if (checkBuckets) {// 存在 上传图片
			InputStream content = new FileInputStream(file);
			ObjectMetadata meta = new ObjectMetadata();
			meta.setContentLength(file.length());
			PutObjectResult result = client.putObject(bucketName, uploadPath,
					content, meta);
			String url=ApplicationConstants.endpoint.replace("http://","http://"+bucketName+".")+"/"+uploadPath;
			return url;
		}
		return null;
	}
	
}
